package com.smile.cloud.warn.dingding;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.URLUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.request.OapiRobotSendRequest.Text;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.smile.cloud.warn.constant.DingTalkConstant;
import com.taobao.api.ApiException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author yangzj
 * @date 2020-11-09 13:50:03
 **/

public class DingTalkUtil {

    public static boolean sendText(String message)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, ApiException {
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp);
        String url = DingTalkConstant.url + "&timestamp=" + timestamp + "&sign=" + sign;
        //设置发送消息
        Text text = new Text();
        text.setContent(message);
        //设置发送对象
        //OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        //at.setIsAtAll(true);
        //实例化请求对象
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        request.setText(text);
        //request.setAt(at);
        //实例化发送对象
        DingTalkClient client = new DefaultDingTalkClient(url);
        OapiRobotSendResponse response = client.execute(request);
        if (response.isSuccess()){
            return true;
        }
        return false;
    }

    private static String getSign(Long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + DingTalkConstant.secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(DingTalkConstant.secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String encode = Base64.encode(signData);
        return URLUtil.encode(encode, "UTF-8");
    }


}
